package com.hdax.dm.user.service.impl;

import cn.hutool.crypto.digest.DigestAlgorithm;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dm.common.code.CodeEnum;
import com.hdax.dm.common.exception.DmException;
import com.hdax.dm.entity.user.User;
import com.hdax.dm.user.mappers.UserMapper;
import com.hdax.dm.user.service.UserService;
import com.hdax.dm.user.service.UserenrollService;
import com.hdax.dm.utils.CommonResponse;
import com.hdax.dm.utils.ResponseUtil;
import org.apache.tomcat.util.digester.Digester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Map;
@Service
public class UserenrollServiceImpl extends ServiceImpl<UserMapper, User> implements UserenrollService {


    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public CommonResponse userenroll(Map<String, String> params) throws DmException {
        User save = new User();
        String phone =params.get("phone");
        String vcode = params.get("vcode");
        String redisKey= phone +"_vcode";
        String password = params.get("password");


        //redis存储的真实有效的验证码
        String code = stringRedisTemplate.opsForValue().get(redisKey);
        if(vcode==null ||!vcode.equals(code)){
            throw new DmException(CodeEnum.USER_VCODE_INVALID);
        }
        User user = userService.user(phone);

        if(vcode.equals(code)) {

            if (user == null) {
                save.setPhone(phone);
                save.setNickName("大米");
                if (password != null && !password.equals("")) {
                    String digestHex = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
                    save.setPassword(digestHex);
                }

                userService.save(save);

            }
        }

        return ResponseUtil.returnSuccess(null);
    }
}
